var http = require('http');
var url = require('url');
var fs = require('fs');
var path = require('path');
var Expires = {
    maxAge: 60 * 60 * 24, // 1天，单位秒
};
var zlib = require('zlib');
const mimeList = {
    'html': 'text/html; charset=utf-8',
    'js': 'application/javascript',
    'css': 'text/css',
    'png': 'image/png'
};

var server = http.createServer(function (req, res) {
    var pathname = url.parse(req.url).pathname;//解析路径
    var resourcePath = path.resolve(__dirname, "../html", pathname.slice(1));
    var suffix = path.extname(pathname).slice(1);//获取后缀
    var contentType = mimeList[suffix];
    if (fs.existsSync(resourcePath)) {//判断资源是否存在，存在则读取
        fs.stat(resourcePath, function (err, stat) {
            var lastModified = stat.mtime.toUTCString();
            var ifModifiedSince = "If-Modified-Since".toLowerCase();
            var expires = new Date();
            res.setHeader("Last-Modified", lastModified);
            res.setHeader('Content-Type', contentType);
            res.setHeader("Expires", expires.toUTCString());
            res.setHeader("Cache-Control", "max-age=" + Expires.maxAge);
            expires.setTime(expires.getTime() + Expires.maxAge * 1000);
            if (req.headers[ifModifiedSince] && lastModified == req.headers[ifModifiedSince]) {//实现304逻辑
                res.writeHead(304, "Not Modified");
                res.end();
            } else {
                var resource = fs.createReadStream(resourcePath);
                var acceptEncoding = req.headers['accept-encoding'];
                if (acceptEncoding && acceptEncoding.indexOf('gzip') != -1 && suffix !== 'html') {
                    resource.pipe(zlib.createGzip()).pipe(res);
                } else {
                    res.writeHead(200, "Ok");
                    resource.pipe(res);
                }
            }
        })
    } else {
        res.writeHead(404, contentType && { 'Content-Type': contentType });
        res.write('No Found');
        res.end();
    }
});
server.listen(9000, function () {
    console.log('you are listening port 9000');
});